package com.yhh.college_information_platform.controller;

import com.yhh.college_information_platform.annotation.RequireAuth;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.Result;
import com.yhh.college_information_platform.service.LikeService;
import com.yhh.college_information_platform.vo.ResourceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 点赞管理Controller（所有接口需要登录）
 *
 * @author yhh
 * @date 2025-10-25
 */
@Slf4j
@RestController
@RequestMapping("/like")
@RequireAuth  // 整个Controller都需要登录
public class LikeController {

    @Autowired
    private LikeService likeService;

    /**
     * 点赞资料
     */
    @PostMapping("/{resourceId}")
    public Result<Void> addLike(@PathVariable Long resourceId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            // 兜底：从 Authorization 头部解析 token 获取 userId，防止拦截器未生效时出现空值
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            try {
                // 直接使用 JwtUtil 的静态方法或注入方式，这里简化为通过Spring获取
                com.yhh.college_information_platform.utils.JwtUtil jwtUtil =
                        org.springframework.web.context.support.WebApplicationContextUtils
                                .getRequiredWebApplicationContext(request.getServletContext())
                                .getBean(com.yhh.college_information_platform.utils.JwtUtil.class);
                if (token != null && jwtUtil.validateToken(token)) {
                    userId = jwtUtil.getUserIdFromToken(token);
                    request.setAttribute("userId", userId);
                }
            } catch (Exception ignore) {}
        }

        log.info("=== LikeController.addLike - resourceId={}, resolved userId={} ===", resourceId, userId);
        likeService.addLike(userId, resourceId);
        return Result.success();
    }

    /**
     * 取消点赞
     */
    @DeleteMapping("/{resourceId}")
    public Result<Void> removeLike(@PathVariable Long resourceId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        likeService.removeLike(userId, resourceId);
        return Result.success();
    }

    /**
     * 判断是否点赞
     */
    @GetMapping("/check/{resourceId}")
    public Result<Boolean> isLiked(@PathVariable Long resourceId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        Boolean isLiked = likeService.isLiked(userId, resourceId);
        return Result.success(isLiked);
    }

    /**
     * 获取用户的点赞列表
     */
    @GetMapping("/my")
    public Result<PageResult<ResourceVO>> getUserLikes(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        PageResult<ResourceVO> pageResult = likeService.getUserLikes(userId, current, size);
        return Result.success(pageResult);
    }
}

